﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class PlatformRange
{
    public Vector2 left;
    public Vector2 right;
}


public class MapBottom : MonoBehaviour
{
    public List<PlatformRange> platformRanges = new List<PlatformRange>();
    private void Start()
    {
        platformRanges.Clear();
        GameObject[] obj= GameObject.FindGameObjectsWithTag("Contact");
        for (int i = 0; i < obj.Length; i++)
        {
            BoxCollider2D box= obj[i].GetComponent<BoxCollider2D>();
            float boxHalfWeight = box.size.x * 0.5f;
            float boxHalfHeight = box.size.y * 0.5f;
            float height = box.offset.y + box.transform.position.y + boxHalfHeight;
            Vector2 l = new Vector2(box.transform.position.x- boxHalfWeight + box.offset.x+0.15f, height);
            Vector2 r = new Vector2(box.transform.position.x + boxHalfWeight + box.offset.x-0.15f, height);
            platformRanges.Add(new PlatformRange() { left=l,right=r});
        }
    }

    public void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag=="Player")
        {
            var damage= collision.GetComponent<IDamage>();
            if (damage!=null)
            {
                damage.OnDamage(gameObject,collision.transform.position,1);
                StartCoroutine(ReStartPos(2,collision.transform));
            }
        }
    }

    public IEnumerator ReStartPos(float time,Transform tr)
    {
        yield return new WaitForSeconds(time);
        ReStartPos(tr);
    }
    public void ReStartPos(Transform tr)
    {
        float distance = float.MaxValue;
        Vector2 nerestPos = DefaultData.playerDefultPos;
        for (int i = 0; i < platformRanges.Count; i++)
        {
            if (tr.position.x> platformRanges[i].left.x)
            {
                if (tr.position.x<platformRanges[i].right.x)
                {
                    tr.transform.position = new Vector2(tr.position.x, platformRanges[i].left.y);
                    return;

                }
            }
            
            
        }
       
        for (int i = 0; i < platformRanges.Count; i++)
        {
            float disx = Mathf.Abs(tr.position.x-platformRanges[i].left.x);
            float disy = Mathf.Abs(tr.position.x-platformRanges[i].right.x);
            if (distance>disx)
            {
                distance = disx;
                nerestPos = platformRanges[i].left;
            }
            if (distance>disy)
            {
                distance = disy;
                nerestPos = platformRanges[i].right;
            }
        }
        tr.transform.position = nerestPos;
        
    }
}
